package com.luo.controller;

import com.alibaba.fastjson.JSON;
import com.luo.model.Goods;
import com.luo.model.OneClass;
import com.luo.model.Result;
import com.luo.model.TwoClass;
import com.luo.service.ClassService;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

@WebServlet(urlPatterns = "/home/category/head")
public class ClassController extends HttpServlet{

    ClassService classService = new ClassService();

    @Override
    protected void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {

        //将查到的内容写成一个列表
        Result result = new Result();
        List<Object> list = new ArrayList<>();
        List<OneClass> oneClasses = classService.queryAllOneClass();
        for (OneClass oneClass : oneClasses) {
            //将每个大类中的子类数据查询出
            List<TwoClass> twoClasses = classService.queryTwoClassByOneId(oneClass);
            List<Object> list1 = new ArrayList<>();
            for (TwoClass twoClass : twoClasses) {
                list1.add(twoClass);
            }
            oneClass.setChildren(list1);

            //将每个大类中的好物查询出来
            List<Goods> goods = classService.queryGoodsByOneId(oneClass);
            List<Object> list2 = new ArrayList<>();
            for (Goods good : goods) {
                list2.add(good);
            }
            oneClass.setGoods(list2);

            //将第一大类存于集合中
            list.add(oneClass);
        }

        //封装为对象
        result.setCode("1");
        result.setMsg("添加成功");
        result.setResult(list);

        //将对象解析为json
        String jsonString = JSON.toJSONString(result);

        //返回到前端
        resp.setContentType("text/json;charset=utf-8");
        resp.getWriter().write(jsonString);
        resp.getWriter().close();
    }
}
